package com.lagou.module.filter;

import com.lagou.module.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/mainPage.jsp", "/manageClassGrade.jsp", "/manageStudent.jsp"})
public class LoginFilter implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 1. 过滤
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;

        // 2.session  的判断
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute("user");
        // System.out.println("过滤器中：user = " + user);
        // 获取Servlet的请求路径
        String servletPath = httpServletRequest.getServletPath();
        String userName = null;
        if (null != user && servletPath.contains("adminLoginServlet")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 2.2 若没有登录，则查询cookie信息中是否已经保存账号和密码信息
            Cookie[] cookies = httpServletRequest.getCookies();
            // System.out.println("数组中：" + Arrays.toString(cookies));
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    // System.out.println("拦截器中：name = " + name);
                    if ("userName".equals(name)) {
                        userName = name;
                        break;
                    }
                }
            }
        }
        if (null != userName) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            servletRequest.getRequestDispatcher("index.jsp").forward(servletRequest, servletResponse);
        }
    }

    public void init(FilterConfig config) throws ServletException {
    }

}
